﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GS.Cricket.Web.mapclass;
using System.Web.UI.HtmlControls;

namespace GS.Cricket.Web
{
    public partial class Match : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["validuser"] != null)
            {
                if (!(Boolean)Session["validuser"])
                {
                    Panel_TeamAAdmin.Visible = false;
                    Panel_TeamBAdmin.Visible = false;
                }
            }
            else
            {
                Panel_TeamAAdmin.Visible = false;
                Panel_TeamBAdmin.Visible = false;
            }

            if (!IsPostBack)
            {
                int matchId = Request.QueryString.Count <= 0 ? -1 : Int32.Parse(Request.QueryString[0]);
                ViewState["MatchId"] = matchId;

                var matchService = new GS.Cricket.Service.Impl.MatchService();
                var match = matchService.GetById(matchId);

                if (matchId != -1)
                {
                    ViewState["TeamAId"] = match.TeamA;
                    ViewState["TeamBId"] = match.TeamB;

                    TeamGridBind(match.TeamA, matchId, TeamAGrid, Label_TeamA, DropDownList_TeamA);
                    TeamGridBind(match.TeamB, matchId, TeamBGrid, Label_TeamB, DropDownList_TeamB);
                    UpdateTeamMatchSummary();
                }
            }
        }

        private void TeamGridBind(int teamId, int matchId, GridView TeamGrid, Label TeamLabel, DropDownList PlayerSelector)
        {
            var teamService = new GS.Cricket.Service.Impl.TeamService();
            var team = teamService.GetById(teamId);
            TeamLabel.Text = team.Name;

            var playerService = new GS.Cricket.Service.Impl.PlayerService();
            var players = playerService.GetByTeam(teamId);

            var matchPlayerService = new GS.Cricket.Service.Impl.MatchPlayerService();
            var matchPlayers = matchPlayerService.GetByMatch(matchId);

            var scorecard = new List<Scorecard>();

            foreach (var matchPlayer in matchPlayers)
            {
                var player = players.FirstOrDefault(p => p.Id.Equals(matchPlayer.PlayerId));
                if (player != null)
                {
                    var score = new Scorecard();
                    //{
                    score.Id = matchPlayer.Id;
                    score.PlayerId = matchPlayer.PlayerId;
                    score.Name = player.Name;
                    score.RunsScored = matchPlayer.RunsScored.ToString();
                    //};

                    scorecard.Add(score);
                }
            }


            // Add Total Score
            TeamGrid.DataSource = scorecard.Select(score => score);
            TeamGrid.AutoGenerateColumns = false;
            TeamGrid.DataBind();


            // Load the dropdowns
            var remainingPlayers = players.Select(p => p).Where(p => !matchPlayers.Any(mp => mp.PlayerId.Equals(p.Id)));
            PlayerSelector.DataSource = remainingPlayers.Select(rp => rp);
            PlayerSelector.DataTextField = "Name";
            PlayerSelector.DataValueField = "Id";
            PlayerSelector.DataBind();
        }

        protected void Button_AddScoreTeamAClick(object sender, EventArgs e)
        {
            if (DropDownList_TeamA.SelectedIndex == -1)
            {
                Label_MatchTeamAError.Text = "Invalid player selection.";
            }
            else
            {
                var score = new Scorecard()
                {
                    PlayerId = Int32.Parse(DropDownList_TeamA.SelectedValue),
                    Name = DropDownList_TeamA.SelectedItem.Text,
                    RunsScored = TextBox_TeamARunsScored.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamARunsScored.Text.Trim()
                };

                var matchPlayer = new GS.Cricket.Entities.MatchPlayer()
                {
                    PlayerId = score.PlayerId,
                    RunsScored = Int32.Parse(score.RunsScored),
                    MatchId = Int32.Parse(ViewState["MatchId"].ToString())
                };

                var matchPlayerService = new GS.Cricket.Service.Impl.MatchPlayerService();
                matchPlayerService.Add(matchPlayer);

                TeamGridBind(Int32.Parse(ViewState["TeamAId"].ToString()),
                                Int32.Parse(ViewState["MatchId"].ToString()),
                                TeamAGrid, Label_TeamA, DropDownList_TeamA);

            }
        }

        protected void Button_AddScoreTeamBClick(object sender, EventArgs e)
        {
            if (DropDownList_TeamB.SelectedIndex == -1)
            {
                Label_MatchTeamBError.Text = "Invalid player selection.";
            }
            else
            {
                var score = new Scorecard()
                {
                    PlayerId = Int32.Parse(DropDownList_TeamB.SelectedValue),
                    Name = DropDownList_TeamB.SelectedItem.Text,
                    RunsScored = TextBox_TeamBRunsScored.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamBRunsScored.Text.Trim()
                };

                var matchPlayer = new GS.Cricket.Entities.MatchPlayer()
                {
                    PlayerId = score.PlayerId,
                    RunsScored = Int32.Parse(score.RunsScored),
                    MatchId = Int32.Parse(ViewState["MatchId"].ToString())
                };

                var matchPlayerService = new GS.Cricket.Service.Impl.MatchPlayerService();
                matchPlayerService.Add(matchPlayer);

                TeamGridBind(Int32.Parse(ViewState["TeamBId"].ToString()),
                                Int32.Parse(ViewState["MatchId"].ToString()),
                                TeamBGrid, Label_TeamB, DropDownList_TeamB);

            }
        }

        protected void Button_AddUpdateTeamAStatsClick(object sender, EventArgs e)
        {
            //var extras = TextBox_TeamAExtras.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamAExtras.Text.Trim();
            //var oversPlayed = TextBox_TeamAOversPlayed.Text.Trim().Equals(String.Empty) ? "0.0" : TextBox_TeamAOversPlayed.Text.Trim();
            //var wickets = TextBox_TeamAWickets.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamAWickets.Text.Trim();
            //var totalRuns = TextBox_TeamATotalRuns.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamATotalRuns.Text.Trim();
            //var hasWon = RadioButton_TeamAWinner.Checked;
            //var matchId = Int32.Parse(ViewState["MatchId"].ToString());
            //var teamAId = Int32.Parse(ViewState["TeamAId"].ToString());
            //var teamBId = Int32.Parse(ViewState["TeamBId"].ToString());

            
            UpdateTeamStats(
            TextBox_TeamAExtras, TextBox_TeamAOversPlayed, TextBox_TeamAWickets, TextBox_TeamATotalRuns, RadioButton_TeamAWinner,
            Label_TeamA, Label_TeamB, Label_TeamAExtras, Label_TeamATotalOvers, Label_TeamAWickets, Label_TeamATotalRuns, 
            1);

            //var matchTeamService = new GS.Cricket.Service.Impl.MatchTeamService();
            //var matchTeams = matchTeamService.GetAll().ToList();
            //var teamAStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamAId))).FirstOrDefault();
            //var teamBStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamBId))).FirstOrDefault();

            //if (teamAStats == null)
            //{
            //    var matchTeam = new GS.Cricket.Entities.MatchTeam()
            //    {
            //        MatchId = matchId,
            //        OversPlayed = Double.Parse(oversPlayed),
            //        RunsScored = Int32.Parse(totalRuns),
            //        TeamId = teamAId,
            //        Wickets = Int32.Parse(wickets),
            //        Extras = Int32.Parse(extras),
            //        HasWon = hasWon
            //    };

            //    var matchTeamId = matchTeamService.Add(matchTeam);
            //}
            //else
            //{
            //    teamAStats.MatchId = matchId;
            //    teamAStats.OversPlayed = Double.Parse(oversPlayed);
            //    teamAStats.RunsScored = Int32.Parse(totalRuns);
            //    teamAStats.TeamId = teamAId;
            //    teamAStats.Wickets = Int32.Parse(wickets);
            //    teamAStats.Extras = Int32.Parse(extras);
            //    teamAStats.HasWon = hasWon;

            //    matchTeamService.Update(teamAStats);
            //}


            //// Update other team
            //if (teamBStats == null)
            //{
            //    var matchTeam = new GS.Cricket.Entities.MatchTeam()
            //    {
            //        MatchId = matchId,
            //        TeamId = teamBId,
            //        OversBowled = Double.Parse(oversPlayed),
            //        RunsConceeded = int.Parse(totalRuns)
            //    };

            //    var matchTeamId = matchTeamService.Add(matchTeam);
            //}
            //else
            //{
            //    teamBStats.OversBowled = Double.Parse(oversPlayed);
            //    teamBStats.RunsConceeded = int.Parse(totalRuns);

            //    matchTeamService.Update(teamBStats);
            //}


            //Label_TeamAExtras.Text = extras;
            //Label_TeamATotalOvers.Text = oversPlayed;
            //Label_TeamAWickets.Text = wickets;
            //Label_TeamATotalRuns.Text = totalRuns;

            //if (hasWon)
            //{
            //    if (!Label_TeamA.Text.Contains("Winner"))
            //    {
            //        Label_TeamA.Text += "(Winner)";
            //    }

            //    if (Label_TeamB.Text.Contains("Winner"))
            //    {
            //        Label_TeamB.Text = Label_TeamB.Text.Replace("(Winner)", "");
            //    }

            //    // Remove TeamB win status from db
            //    if (teamBStats != null)
            //    {
            //        teamBStats.HasWon = false;
            //        matchTeamService.Update(teamBStats);
            //    }


            //    // Update Match Details
            //    var matchService = new GS.Cricket.Service.Impl.MatchService();
            //    var match = matchService.GetById(Int32.Parse(ViewState["MatchId"].ToString()));
            //    match.Winner = Int32.Parse(ViewState["TeamAId"].ToString());
            //    matchService.Update(match);

            //}
        }

        protected void Button_AddUpdateTeamBStatsClick(object sender, EventArgs e)
        {
            //var extras = TextBox_TeamBExtras.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamBExtras.Text.Trim();
            //var oversPlayed = TextBox_TeamBOversPlayed.Text.Trim().Equals(String.Empty) ? "0.0" : TextBox_TeamBOversPlayed.Text.Trim();
            //var wickets = TextBox_TeamBWickets.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamBWickets.Text.Trim();
            //var totalRuns = TextBox_TeamBTotalRuns.Text.Trim().Equals(String.Empty) ? "0" : TextBox_TeamBTotalRuns.Text.Trim();
            ////var hasWon = RadioButton_TeamBWinner.Checked;
            //var matchId = Int32.Parse(ViewState["MatchId"].ToString());
            //var teamAId = Int32.Parse(ViewState["TeamAId"].ToString());
            //var teamBId = Int32.Parse(ViewState["TeamBId"].ToString());


            UpdateTeamStats(
            TextBox_TeamBExtras, TextBox_TeamBOversPlayed, TextBox_TeamBWickets, TextBox_TeamBTotalRuns, RadioButton_TeamBWinner,
            Label_TeamA, Label_TeamB, Label_TeamBExtras, Label_TeamBTotalOvers, Label_TeamBWickets, Label_TeamBTotalRuns,
            2);

            //var matchTeamService = new GS.Cricket.Service.Impl.MatchTeamService();
            //var matchTeams = matchTeamService.GetAll().ToList();
            //var teamAStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamAId))).FirstOrDefault();
            //var teamBStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamBId))).FirstOrDefault();

            //if (teamBStats == null)
            //{
            //    var matchTeam = new GS.Cricket.Entities.MatchTeam()
            //    {
            //        MatchId = matchId,
            //        OversPlayed = Double.Parse(oversPlayed),
            //        RunsScored = Int32.Parse(totalRuns),
            //        TeamId = teamBId,
            //        Wickets = Int32.Parse(wickets),
            //        Extras = Int32.Parse(extras),
            //        HasWon = hasWon
            //    };

            //    var matchTeamId = matchTeamService.Add(matchTeam);
            //}
            //else
            //{
            //    teamBStats.MatchId = matchId;
            //    teamBStats.OversPlayed = Double.Parse(oversPlayed);
            //    teamBStats.RunsScored = Int32.Parse(totalRuns);
            //    teamBStats.TeamId = teamBId;
            //    teamBStats.Wickets = Int32.Parse(wickets);
            //    teamBStats.Extras = Int32.Parse(extras);
            //    teamBStats.HasWon = hasWon;

            //    matchTeamService.Update(teamBStats);
            //}


            //// Update other team
            //if (teamAStats == null)
            //{
            //    var matchTeam = new GS.Cricket.Entities.MatchTeam()
            //    {
            //        MatchId = matchId,
            //        TeamId = teamBId,
            //        OversBowled = Double.Parse(oversPlayed),
            //        RunsConceeded = int.Parse(totalRuns)
            //    };

            //    var matchTeamId = matchTeamService.Add(matchTeam);
            //}
            //else
            //{
            //    teamAStats.OversBowled = Double.Parse(oversPlayed);
            //    teamAStats.RunsConceeded = int.Parse(totalRuns);

            //    matchTeamService.Update(teamAStats);
            //}

            //Label_TeamBExtras.Text = extras;
            //Label_TeamBTotalOvers.Text = oversPlayed;
            //Label_TeamBWickets.Text = wickets;
            //Label_TeamBTotalRuns.Text = totalRuns;
            //if (hasWon)
            //{
            //    if (!Label_TeamB.Text.Contains("Winner"))
            //    {
            //        Label_TeamB.Text += "(Winner)";
            //    }

            //    if (Label_TeamA.Text.Contains("Winner"))
            //    {
            //        Label_TeamA.Text = Label_TeamA.Text.Replace("(Winner)", "");
            //    }


            //    // Remove TeamA win status from db
            //    if (teamAStats != null)
            //    {
            //        teamAStats.HasWon = false;
            //        matchTeamService.Update(teamAStats);
            //    }


            //    // Update Match Details
            //    var matchService = new GS.Cricket.Service.Impl.MatchService();
            //    var match = matchService.GetById(Int32.Parse(ViewState["MatchId"].ToString()));
            //    match.Winner = Int32.Parse(ViewState["TeamBId"].ToString());
            //    matchService.Update(match);
            //}
        }

        protected void Button_DeleteScoreTeamAClick(object sender, EventArgs e)
        {
            if (TeamAGrid.SelectedIndex == -1)
            {
                Label_MatchTeamAError.Text = "Invalid selection";
            }
            else
            {
                var scoreId = Int32.Parse(TeamAGrid.SelectedValue.ToString());
                var matchPlayer = new GS.Cricket.Service.Impl.MatchPlayerService();
                matchPlayer.Delete(scoreId);

                TeamGridBind(Int32.Parse(ViewState["TeamAId"].ToString()),
                                Int32.Parse(ViewState["MatchId"].ToString()),
                                TeamAGrid, Label_TeamA, DropDownList_TeamA);
            }
        }

        protected void Button_DeleteScoreTeamBClick(object sender, EventArgs e)
        {
            if (TeamBGrid.SelectedIndex == -1)
            {
                Label_MatchTeamBError.Text = "Invalid selection";
            }
            else
            {
                var scoreId = Int32.Parse(TeamBGrid.SelectedValue.ToString());
                var matchPlayer = new GS.Cricket.Service.Impl.MatchPlayerService();
                matchPlayer.Delete(scoreId);

                TeamGridBind(Int32.Parse(ViewState["TeamBId"].ToString()),
                                Int32.Parse(ViewState["MatchId"].ToString()),
                                TeamBGrid, Label_TeamB, DropDownList_TeamB);
            }
        }

        protected void UpdateTeamMatchSummary()
        {
            var matchTeamService = new GS.Cricket.Service.Impl.MatchTeamService();
            var matchId = Int32.Parse(ViewState["MatchId"].ToString());
            var teamAId = Int32.Parse(ViewState["TeamAId"].ToString());
            var teamBId = Int32.Parse(ViewState["TeamBId"].ToString());
            var matchTeams = matchTeamService.GetAll().ToList();
            var teamAStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamAId))).FirstOrDefault();
            var teamBStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamBId))).FirstOrDefault();

            if (teamAStats != null)
            {
                Label_TeamAExtras.Text = teamAStats.Extras.ToString();
                Label_TeamATotalOvers.Text = teamAStats.OversPlayed.ToString();
                Label_TeamAWickets.Text = teamAStats.Wickets.ToString();
                Label_TeamATotalRuns.Text = teamAStats.RunsScored.ToString();
                TextBox_TeamAExtras.Text = teamAStats.Extras.ToString();
                TextBox_TeamAOversPlayed.Text = teamAStats.OversPlayed.ToString();
                TextBox_TeamAWickets.Text = teamAStats.Wickets.ToString();
                TextBox_TeamATotalRuns.Text = teamAStats.RunsScored.ToString();

                if (teamAStats.HasWon)
                {
                    Label_TeamA.Text += "(Winner)";
                    RadioButton_TeamAWinner.Checked = true;
                }
            }

            if (teamBStats != null)
            {
                Label_TeamBExtras.Text = teamBStats.Extras.ToString();
                Label_TeamBTotalOvers.Text = teamBStats.OversPlayed.ToString();
                Label_TeamBWickets.Text = teamBStats.Wickets.ToString();
                Label_TeamBTotalRuns.Text = teamBStats.RunsScored.ToString();
                TextBox_TeamBExtras.Text = teamBStats.Extras.ToString();
                TextBox_TeamBOversPlayed.Text = teamBStats.OversPlayed.ToString();
                TextBox_TeamBWickets.Text = teamBStats.Wickets.ToString();
                TextBox_TeamBTotalRuns.Text = teamBStats.RunsScored.ToString();



                if (teamBStats.HasWon)
                {
                    Label_TeamB.Text += "(Winner)";
                    RadioButton_TeamBWinner.Checked = true;
                }
            }

        }

        private void UpdateTeamStats(
            TextBox tExtras, TextBox tOversPlayed, TextBox tWickets, TextBox tTotalRuns, RadioButton rWinner,
            Label lTeamA, Label lTeamB, Label lExtras, Label lOversPlayed, Label lWickets, Label lTotalRuns, 
            int teamSelector)
        {
            var extras = tExtras.Text.Trim().Equals(String.Empty) ? "0" : tExtras.Text.Trim();
            var oversPlayed = tOversPlayed.Text.Trim().Equals(String.Empty) ? "0.0" : tOversPlayed.Text.Trim();
            var wickets = tWickets.Text.Trim().Equals(String.Empty) ? "0" : tWickets.Text.Trim();
            var totalRuns = tTotalRuns.Text.Trim().Equals(String.Empty) ? "0" : tTotalRuns.Text.Trim();
            var hasWon = rWinner.Checked;
            var matchId = Int32.Parse(ViewState["MatchId"].ToString());
            var teamAId = Int32.Parse(ViewState["TeamAId"].ToString());
            var teamBId = Int32.Parse(ViewState["TeamBId"].ToString());


            var matchTeamService = new GS.Cricket.Service.Impl.MatchTeamService();
            var matchTeams = matchTeamService.GetAll().ToList();
            var teamAStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamAId))).FirstOrDefault();
            var teamBStats = matchTeams.Where(mt => (mt.MatchId.Equals(matchId) && mt.TeamId.Equals(teamBId))).FirstOrDefault();

            // Update current team
            var currentTeam = (teamSelector == 1) ? teamAStats : teamBStats;
            var otherTeam = (teamSelector == 1) ? teamBStats : teamAStats;
            if (currentTeam == null)
            {
                var matchTeam = new GS.Cricket.Entities.MatchTeam()
                {
                    MatchId = matchId,
                    OversPlayed = Double.Parse(oversPlayed),
                    RunsScored = Int32.Parse(totalRuns),
                    TeamId = (teamSelector == 1) ? teamAId : teamBId,
                    Wickets = Int32.Parse(wickets),
                    Extras = Int32.Parse(extras),
                    HasWon = hasWon
                };

                var matchTeamId = matchTeamService.Add(matchTeam);
            }
            else
            {
                currentTeam.MatchId = matchId;
                currentTeam.OversPlayed = Double.Parse(oversPlayed);
                currentTeam.RunsScored = Int32.Parse(totalRuns);
                currentTeam.TeamId = (teamSelector == 1) ? teamAId : teamBId;
                currentTeam.Wickets = Int32.Parse(wickets);
                currentTeam.Extras = Int32.Parse(extras);
                currentTeam.HasWon = hasWon;

                matchTeamService.Update(currentTeam);
            }


            // Update other team
            if (otherTeam == null)
            {
                var matchTeam = new GS.Cricket.Entities.MatchTeam()
                {
                    MatchId = matchId,
                    TeamId = (teamSelector == 1) ? teamBId : teamAId,
                    OversBowled = Double.Parse(oversPlayed),
                    RunsConceeded = int.Parse(totalRuns)
                };

                var matchTeamId = matchTeamService.Add(matchTeam);
            }
            else
            {
                otherTeam.OversBowled = Double.Parse(oversPlayed);
                otherTeam.RunsConceeded = int.Parse(totalRuns);

                matchTeamService.Update(otherTeam);
            }


            lExtras.Text = extras;
            lOversPlayed.Text = oversPlayed;
            lWickets.Text = wickets;
            lTotalRuns.Text = totalRuns;

            if (hasWon)
            {
                var CurrentTeamLabel = (teamSelector == 1) ? lTeamA : lTeamB;
                var OtherTeamLabel = (teamSelector == 1) ? lTeamB : lTeamA;

                if (!CurrentTeamLabel.Text.Contains("Winner"))
                {
                    CurrentTeamLabel.Text += "(Winner)";
                }

                if (OtherTeamLabel.Text.Contains("Winner"))
                {
                    OtherTeamLabel.Text = OtherTeamLabel.Text.Replace("(Winner)", "");
                }

                // Remove TeamB win status from db
                if (otherTeam != null)
                {
                    otherTeam.HasWon = false;
                    matchTeamService.Update(otherTeam);
                }


                // Update Match Details
                var matchService = new GS.Cricket.Service.Impl.MatchService();
                var match = matchService.GetById(matchId);
                match.Winner = (teamSelector == 1) ? teamAId : teamBId;
                matchService.Update(match);

            }
        }


        #region Important! Select Row Capability
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            AddRowSelectToGridView(TeamAGrid);
            AddRowSelectToGridView(TeamBGrid);
            base.Render(writer);
        }

        private void AddRowSelectToGridView(GridView gv)
        {
            foreach (GridViewRow row in gv.Rows)
            {
                row.Attributes["onmouseover"] = "this.style.cursor='pointer'";
                row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true));
            }
        }
        #endregion

    }
}